// must include here for visualmicro to recognize it
#include<Arduino.h>
#include <WiFi.h>

#include "comm.hpp"
#include "misc.hpp"
#include "Preferences.h"
#include "parseCMD/parseCMD.hpp"
#include "tempUpdate/tempUpdate.hpp"
#include "fanDriver/fanDriver.hpp"
#include "Global/globalVars.hpp"
//#include "../tPumpShared/COMM/comm.hpp"

int onlineServiceLooper = 0;
#define OL_LOOP_ACTIONS 2
int defaultOutput = 0;
void setup()
{
	Global::bridgeMode = Comm::init();
	TempReader::init();
	defaultOutput = FanDriver::init(Global::fanOutput);
	Global::fanOutput = defaultOutput;
	if (!Global::bridgeMode) {
		Serial.println("Start in source mode");
		Serial.print("Default fan speed: ");
		Serial.println(Global::fanOutput);
	}
}

int calOutput(int weight) {
	int diff = 100 - defaultOutput;
	int ret = defaultOutput + diff * weight / 100;
	return ret;
}

void loop()
{
	if (Serial.available() > 0) {
		size_t readSize = Serial.readBytesUntil('\n', Global::inputBuffer, sizeof(Global::inputBuffer));
		Global::inputBuffer[readSize] = '\0';
		if (readSize > 0) {
			if (Global::inputBuffer[0] == 0x11) {
				// device control 1
				Serial.println("Start bridge mode");
				Global::bridgeMode = true;
			}
			else if (Global::inputBuffer[0] == 0x12) {
				// device control 2
				Serial.println("Stop bridge mode");
				Global::bridgeMode = false;
			}
			else {
				if (Global::bridgeMode) {
					//Serial.println("Sending");
					//Serial.println(Global::inputBuffer);
					Comm::sendStr(0, Global::inputBuffer);
				}
				else {
					parseCMD(Global::inputBuffer, false);
				}
			}
		}
	}
	else if (Comm::receiveStr(Global::inputBuffer) > 0) {
		if (Global::bridgeMode) {
			print2Serial(Global::inputBuffer);
		}
		else {
			parseCMD(Global::inputBuffer, true);
		}
	}
	else {
		if (onlineServiceLooper % OL_LOOP_ACTIONS == 0) {
			Global::fanTemp = TempReader::readFanTmp();
		}
		else if (onlineServiceLooper % OL_LOOP_ACTIONS == 1) {
			Global::tankTemp = TempReader::readTankTmp();
		}

		const int levels = 5;
		int diffT[levels] = { 8,6,4,2 };
		int outputWeight[levels] = { 100,80,60,30 };

		if (false) {
			if ((Global::tankTemp > -100) && (Global::fanTemp > -100)) {
				if (Global::tankTemp < Global::fanTemp + diffT[levels - 1]) {
					Global::fanOutput = calOutput(0);
					FanDriver::update(Global::fanOutput);
				}
				else {
					for (int idx = 0; idx < levels; idx++) {
						if (Global::tankTemp >= Global::fanTemp + diffT[idx]) {
							Global::fanOutput = calOutput(outputWeight[idx]);
							FanDriver::update(Global::fanOutput);
							break;
						}
					}
				}
			}
		}

		onlineServiceLooper = (onlineServiceLooper + 1) % OL_LOOP_ACTIONS;
	}
}
